<?php

namespace app\api\controller\orderdelivery;

use think\File;
use think\facade\Env;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderdata\Goods;
use app\common\model\orderdata\StorageAreaGoods;
use app\common\model\quotation\QuotationList;
use app\api\controller\Base;
use app\api\controller\Pub;
use app\common\model\orderdelivery\Disposalsite;
use app\common\model\orderdelivery\DeliveryList;
use app\common\model\orderdelivery\Delivery;
use app\common\model\power\Rolepower;
use app\api\controller\mytool\Sendmessage;


class Orderdeliveryware extends Base
{
	/**
	 * 初始化
	 */
	public function initialize()
	{
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(202002);
	}

	/**
	 * 获取订单列表
	 * @return [type] [description]
	 */
	public function list()
	{
		$data = input('get.');
		$data = init_where($data);
		$list = DeliveryList::usergetlist($data, 'ware');
		foreach ($list['list'] as $key => $value) {
			if (empty($value['dispinfo']['DisposalSiteName'])) {
				$list['list'][$key]['Name'] = '暂无';
			} else {
				$list['list'][$key]['Name'] = $value['dispinfo']['DisposalSiteName'];
			}
		}
		$list['tr']['title'] = ['产废单位', '提单时间', '订单状态', '查看', '出库时间'];
		$list['tr']['key'] = ['Name', 'UpTime', 'State', 'DeliveryListId', 'WarehouseTime'];
		$list['tr']['show'] = [true, true, true, true, true];
		return myok($list);
	}

	/**
	 * 获取创建的信息
	 * @return [type] [description]
	 */
	public function getcreateinfo()
	{
		$ndata['Type'] = 'disposalsite';
		$data['DisposalsiteList'] = Disposalsite::usergetlist($ndata, 1, false);
		$data['StateList'] = DeliveryList::STATEARRAY;
		$data['State'] = 0;
		return myok($data);
	}

	/**
	 * 获取订单信息
	 * @return [type] [description]
	 */
	public function getinfo()
	{
		$id = input('id');
		$locallist = input('goodlist');
		if (empty($id)) {
			return myerr('缺少参数，请重新尝试');
		}
		$data = DeliveryList::getinfo($id);
		if (!$data['code']) {
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		if (!empty($data['GoodsList'])) {
			foreach ($data['GoodsList'] as $key => $value) {
				$locallist = $locallist . ',' . $value['GoodId'];
			}
		}
		if(!empty($locallist)){
			$data['waregoodlist'] = StorageAreaGoods::getlist($locallist);
		}else{
			$data['waregoodlist'] =  [];
		}
		$data['CELLPHONE'] = CELLPHONE;
		return myok($data);
	}

	/**
	 * 配货
	 * @return [type] [description]
	 */
	public function disribution()
	{
		$id = input('id');
		$idata = input('post.');
		$goodlist = explode(',', $idata['goodid']);
		$valuelist = explode(',', $idata['value']);
		$storage_good = json_array(input('storage_good'),true);
		$data = DeliveryList::getinfo($id);
		if (!$data['code']) {
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		if ($data['State'] >= DeliveryList::STATETRANSPORT) {
			return myerr('订单已出库无法修改');
		}
		//修改子订单信息
		// $sb = Delivery::screate($id, $goodlist, $valuelist);
		// if (!$sb['code']) {
		// 	return myerr($sb['msg']);
		// }
		
		//修改主订单信息
		$rdata = [];
		if (!empty(input('WarehouseImg')) && input('WarehouseImg') !== $data['WarehouseImg']) {
			$rdata['WarehouseImg'] = input('WarehouseImg');
		}
		if (!empty(input('WarehouseNote')) && input('WarehouseNote') !== $data['WarehouseNote']) {
			$rdata['WarehouseNote'] = input('WarehouseNote');
		}
		if (DeliveryList::STATEWAITOK !== $data['State']) {
			$rdata['State'] = DeliveryList::STATEWAITOK;
		}
		if (!empty($rdata)) {
			$userlogininfo = Pub::getuserid();
			$userid = $userlogininfo['msg'];
			$rdata['WarehouseId'] = $userid;
			$rdata['id'] = $id;
			DeliveryList::user_reinfo($rdata);

		}
		//查询表中的货物
		$deliinfo = Delivery::where('DeliveryListId',$id)->select();
		$deliinfo = arr_id_formate($deliinfo,'StorageAreaGoodsId',true);
		// 修改重量（详情表）
		if (!empty($storage_good)) {
			//输入的数据
			foreach ($storage_good as $v) {
				//查到的数据
				if(!empty($deliinfo[$v['StorageAreaGoodsId']])){
					$value = $deliinfo[$v['StorageAreaGoodsId']];
					//如果重量不相等
					if($v['Weight']!==$value['Weight']){
						$value->Weight = $v['Weight'];
						$value->save();
					}
					//修改后将此删除
					unset($deliinfo[$v['StorageAreaGoodsId']]);
				}else{
					//没有查到数据 创建新的
					Delivery::create([
						'DeliveryListId'     => $id,
						'StorageAreaGoodsId' => $v['StorageAreaGoodsId'],
						'GoodId'             => $v['GoodId'],
						'Weight'             => $v['Weight'],
					]);
				}
			}
		}
		//判断剩余的数据
		$del = [];
		foreach ($deliinfo as $value) {
			$del = $value['DeliveryId'];
		}
		//删除无效数据
		if(!empty($del)){
			Delivery::destroy($del);
		}

		return myok('修改成功');
	}

	/**
	 * 货物出库
	 * @return [type] [description]
	 */
	public function exwarehouse()
	{
		$id = input('id');
		$idata = input('post.');
		$data = DeliveryList::getinfo($id);
		if (!$data['code']) {
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		if ($data['State'] !== DeliveryList::STATEWAITOK) {
			return myerr('状态错误，无法出库');
		}
		//修改库存
		$deli = Delivery::where('DeliveryListId' , $id)->select();
		foreach ($deli as $key => $value) {
			$goodid[] = $value['GoodId'];
			$weight[] = $value['Weight'];
		}

		$sb = Goods::weight_change($goodid, $weight, 'sub');
		if (!$sb['code']) {
			return myerr($sb['msg']);
		}
		//修改库存货物表
		foreach ($deli as $key => $value) {
			$sag = StorageAreaGoods::where('StorageAreaGoodsId',$value['StorageAreaGoodsId'])->find();
			$sag->Weight = $sag->Weight - $value->Weight;
			$sag->save();
		}

		//修改主订单信息
		$rdata = [];
		if (!empty(input('WarehouseImg')) && input('WarehouseImg') !== $data['WarehouseImg']) {
			$rdata['WarehouseImg'] = input('WarehouseImg');
		}
		if (!empty(input('WarehouseNote')) && input('WarehouseNote') !== $data['WarehouseNote']) {
			$rdata['WarehouseNote'] = input('WarehouseNote');
		}
		$rdata['State'] = DeliveryList::STATETRANSPORT;
		$rdata['WarehouseTime'] = date("Y-m-d H:i", time());
		if (!empty($rdata)) {
			$userlogininfo = Pub::getuserid();
			$userid = $userlogininfo['msg'];
			$rdata['WarehouseId'] = $userid;
			$rdata['id'] = $id;
			DeliveryList::user_reinfo($rdata);
		}
		Sendmessage::Orderdelivery(2, $id);
		return myok('出库成功');
	}

	/**
	 * 由于收集员修改订单
	 * 需要用户进行二次确认
	 * @return [type] [description]
	 */
	public function confirmorder()
	{
		$data = input('post.');
		$order = DeliveryList::get($data['id']);
		if (empty($order) || $order->State == DeliveryList::STATEDELETE) {
			return myerr('没有找到您需要的订单');
		}
		if ($order->State !== DeliveryList::STATEWAITOK && $order->State !== DeliveryList::STATETRANSPORT) {
			return myerr('订单状态无法确认');
		}
		if ($order->ConfirmState !== DeliveryList::CONFRIMBUSS) {
			return myerr('订单状态无法确认');
		}
		$order->State = DeliveryList::STATETRANSPORT;
		$order->ConfirmState = DeliveryList::CONFRIMBUSS + DeliveryList::CONFRIMHAWA;
		$order->save();
		return myok('订单确认成功');
	}

	/**
	 * 图片上传
	 * @return [type] [description]
	 */
	public function upimg()
	{
		$type = empty(input('type')) ? 'other' : input('type');
		if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco') {
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
		}
		// 移动到框架应用根目录/public/uploads/ 目录下
		if (!is_null($file)) {
			try {
				$save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\delivery\\' . $type . '\\';
				$info = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
				//echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
				$image = \think\Image::open($save_path . '\\' . $info->getSaveName());
				$image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
				if ($info) {//getSaveName();
					$p = $info->getFilename();
					return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/delivery/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
				} else {
					return json_encode(['status' => 'error', 'data' => $info->getError()]);
				}
			} catch (\Exception $e) {
				return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
			}

		} else {
			return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
		}
	}


	/**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login()
	{
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}
}
